<template>
  <el-form-item :label="label" :prop="prop" :rules="rule" :required="required">
    <el-input
      :placeholder="props.configItem.placeholder"
      clearable
      v-if="type === 'el-input'"
      v-model="formData[props.configItem.formKey]"
      :style="{
        width: props.configItem.width ? props.configItem.width : '120px',
      }"
    />
    <el-select
      v-if="type === 'el-select'"
      clearable
      v-model="formData[props.configItem.formKey]"
      :placeholder="props.configItem.placeholder"
      :style="{
        width: props.configItem.width ? props.configItem.width : '120px',
      }"
    >
      <el-option
        v-for="item in props.configItem.optionData"
        :key="item.value"
        :label="item.label"
        :value="item.value"
        :disabled="item.disabled"
      />
    </el-select>
  </el-form-item>
</template>

<script setup lang="ts">
import { computed, reactive, watch } from "vue";

const emit = defineEmits(["change"]);

const props = defineProps({
  config: {
    type: Array,
    default: () => [],
    required: true,
  },
  configItem: {
    type: Object,
    default: () => {},
  },
  formData: {
    type: Object,
    default: () => {},
  },
});

const formData = reactive({ ...props.formData });

const type = computed(() => props.configItem?.type);
const label = computed(() => props.configItem?.label || "");
const prop = computed(() => props.configItem?.formKey || "");
const required = computed(() => {
  let required = props.configItem?.required === undefined;
  required = required || props.configItem?.required;
  return required;
});
const rule = computed(() => {
  const label = props.configItem?.label || "";
  const isInput = props.configItem?.type === "el-input";
  const message = isInput ? `请输入${label}` : `请选择${label}`;
  const trigger = isInput ? `blur` : `change`;
  return { required, message, trigger };
});

watch(formData, (value) => {
  emit("change", value);
});
</script>

<style scoped lang="scss">
.el-form-item {
  margin-right: 8px;
  margin-bottom: 0;
}
</style>
